<template>
  <Dialog v-model="dialogVisible" title="导入参评人员" width="800px">
    <div v-loading="formLoading">
      <el-steps :active="currentStep" finish-status="success" align-center>
        <el-step title="下载模板" />
        <el-step title="上传文件" />
        <el-step title="数据预览" />
        <el-step title="导入完成" />
      </el-steps>
      
      <!-- 步骤1：下载模板 -->
      <div v-if="currentStep === 0" class="step-content">
        <el-alert
          title="导入说明"
          type="info"
          :closable="false"
          show-icon
        >
          <template #default>
            <p>1. 请先下载导入模板，按照模板格式填写参评人员信息</p>
            <p>2. 支持Excel格式文件(.xlsx, .xls)</p>
            <p>3. 单次最多导入1000条记录</p>
            <p>4. 必填字段：姓名、身份证号、手机号、职业代码</p>
          </template>
        </el-alert>
        
        <div class="template-download">
          <el-button type="primary" @click="downloadTemplate">
            <Icon icon="ep:download" class="mr-5px" />
            下载导入模板
          </el-button>
        </div>
      </div>
      
      <!-- 步骤2：上传文件 -->
      <div v-if="currentStep === 1" class="step-content">
        <el-upload
          ref="uploadRef"
          :action="uploadAction"
          :headers="uploadHeaders"
          :data="uploadData"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :before-upload="beforeUpload"
          :show-file-list="false"
          accept=".xlsx,.xls"
          drag
        >
          <Icon icon="ep:upload-filled" size="40" />
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传xlsx/xls文件，且不超过10MB
            </div>
          </template>
        </el-upload>
        
        <div v-if="uploadedFile" class="uploaded-file">
          <el-tag type="success">{{ uploadedFile.name }}</el-tag>
          <el-button type="text" @click="removeFile">移除</el-button>
        </div>
      </div>
      
      <!-- 步骤3：数据预览 -->
      <div v-if="currentStep === 2" class="step-content">
        <div class="preview-summary">
          <el-alert
            :title="`共解析到 ${previewData.length} 条记录，其中 ${validCount} 条有效，${errorCount} 条错误`"
            :type="errorCount > 0 ? 'warning' : 'success'"
            :closable="false"
          />
        </div>
        
        <el-table :data="previewData" max-height="400" border>
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="name" label="姓名" width="100" />
          <el-table-column prop="idCard" label="身份证号" width="180" />
          <el-table-column prop="phone" label="手机号" width="120" />
          <el-table-column prop="professionCode" label="职业代码" width="120" />
          <el-table-column prop="professionName" label="职业名称" width="150" />
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.isValid ? 'success' : 'danger'">
                {{ row.isValid ? '有效' : '错误' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="errorMessage" label="错误信息" min-width="200" />
        </el-table>
      </div>
      
      <!-- 步骤4：导入完成 -->
      <div v-if="currentStep === 3" class="step-content">
        <el-result
          :icon="importResult.success ? 'success' : 'error'"
          :title="importResult.title"
          :sub-title="importResult.message"
        >
          <template #extra>
            <el-button type="primary" @click="dialogVisible = false">完成</el-button>
          </template>
        </el-result>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="currentStep > 0 && currentStep < 3" @click="prevStep">上一步</el-button>
        <el-button v-if="currentStep < 2" @click="nextStep" :disabled="!canNext">下一步</el-button>
        <el-button v-if="currentStep === 2" @click="confirmImport" type="primary" :disabled="validCount === 0">
          确认导入 ({{ validCount }}条)
        </el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'

defineOptions({ name: 'ImportForm' })

const emit = defineEmits(['success'])

const dialogVisible = ref(false)
const formLoading = ref(false)
const currentStep = ref(0)
const uploadRef = ref()
const uploadedFile = ref(null)
const previewData = ref([])

const uploadAction = ref('/api/eval/candidate/import-preview')
const uploadHeaders = ref({})
const uploadData = reactive({
  planId: undefined
})

const importResult = reactive({
  success: false,
  title: '',
  message: ''
})

const validCount = computed(() => previewData.value.filter(item => item.isValid).length)
const errorCount = computed(() => previewData.value.filter(item => !item.isValid).length)
const canNext = computed(() => {
  if (currentStep.value === 0) return true
  if (currentStep.value === 1) return uploadedFile.value !== null
  return false
})

/** 打开弹窗 */
const open = async (planId: number) => {
  dialogVisible.value = true
  uploadData.planId = planId
  resetForm()
}

/** 重置表单 */
const resetForm = () => {
  currentStep.value = 0
  uploadedFile.value = null
  previewData.value = []
  formLoading.value = false
}

/** 下载模板 */
const downloadTemplate = () => {
  // TODO: 实现下载模板功能
  const link = document.createElement('a')
  link.href = '/api/eval/candidate/download-template'
  link.download = '参评人员导入模板.xlsx'
  link.click()
}

/** 上传前检查 */
const beforeUpload = (file: File) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                  file.type === 'application/vnd.ms-excel'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isExcel) {
    ElMessage.error('只能上传Excel文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!')
    return false
  }
  
  formLoading.value = true
  return true
}

/** 上传成功 */
const handleUploadSuccess = (response: any, file: File) => {
  formLoading.value = false
  uploadedFile.value = file
  previewData.value = response.data || []
  ElMessage.success('文件上传成功')
}

/** 上传失败 */
const handleUploadError = () => {
  formLoading.value = false
  ElMessage.error('文件上传失败')
}

/** 移除文件 */
const removeFile = () => {
  uploadedFile.value = null
  previewData.value = []
}

/** 上一步 */
const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

/** 下一步 */
const nextStep = () => {
  if (currentStep.value < 3) {
    currentStep.value++
  }
}

/** 确认导入 */
const confirmImport = async () => {
  try {
    formLoading.value = true
    
    const validData = previewData.value.filter(item => item.isValid)
    // TODO: 调用确认导入的API
    // await confirmImportCandidates({ planId: uploadData.planId, data: validData })
    
    importResult.success = true
    importResult.title = '导入成功'
    importResult.message = `成功导入 ${validData.length} 条参评人员记录`
    
    currentStep.value = 3
    emit('success')
  } catch (error) {
    console.error('导入失败:', error)
    importResult.success = false
    importResult.title = '导入失败'
    importResult.message = '导入过程中发生错误，请重试'
    currentStep.value = 3
  } finally {
    formLoading.value = false
  }
}

defineExpose({ open })
</script>

<style scoped>
.step-content {
  margin: 30px 0;
  min-height: 300px;
}

.template-download {
  text-align: center;
  margin-top: 30px;
}

.uploaded-file {
  margin-top: 20px;
  text-align: center;
}

.preview-summary {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
